package songhq.com.mongo.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import songhq.com.mongo.utils.EasyExcelUtil;
import songhq.com.mongo.vo.SchoolScheduleVO;

@Service
public class ExcelService {
	
	@Autowired
	private MongoTemplate mongoTemplate;

	public void readSchedule(MultipartFile excel) throws IOException {
		List<Object> objects = EasyExcelUtil.readExcel(excel, new SchoolScheduleVO(), 1, 2);
		if(objects ==null ||objects.size()==0) {
			return ;
		}
		insertData(objects);
		
		
	}
	//存入mongo中，批量存入，2000个存一次
	private void insertData(List<Object> objects){

		int count = objects.size();
		int size = 2000;

		int remainder = count%size;

		int num = 0;
		if (count <=size){
			num = 1;
		}else if (remainder == 0){
			num = count / size;
		}else {
			num = count / size + 1;
		}
		int a = 0;
		List<JSONObject> mongoCouponVoList = new ArrayList<>();
		for (int i=0; i<num; i++){
			if (i==num-1 || num==1){
				a=count;
			}else {
				a=(i+1)*size;
			}
			for (int j=i*size; j<a; j++){
				Object object = objects.get(j);
				String jsonString = JSON.toJSONString(object);
				JSONObject parseObject = JSON.parseObject(jsonString);
				parseObject.remove("cellStyleMap");
				parseObject.put("_id", j);
				mongoCouponVoList.add(parseObject);
			}
			//批量插入
			BulkOperations ops = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, "scholl3v3Schedule");
			ops.insert(mongoCouponVoList);
			ops.execute();
			mongoCouponVoList.clear();
		}
	}

}
